﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web.Mvc;
using DataAccess.DB;
using DuocThaiBinh.Common;
using DuocThaiBinh.HtmlHelpers;
using DuocThaiBinh.HtmlHelpers.ExportToExcel;
using Newtonsoft.Json;
using PagedList;

namespace DuocThaiBinh.Controllers
{
    public class CauHinhSanPhamTrongKhoController : BaseController
    {
        [Authorize(Roles = "Administrator")]
        public ActionResult Index()
        {
            CuaHang curCuaHang = GetCurrentCuaHang();
            ViewBag.KhoID = new SelectList(curCuaHang.Khoes.OrderBy(p => p.TenKho), "ID", "TenKho");
            return View();
        }

        [Authorize(Roles = "Administrator")]
        public JsonResult IndexGet(int id = 0)
        {
            var SanPhams = new List<SanPham>();
            if (id == 0)
            {
                return Json(new
                {
                    data = SanPhams.Select(x => new { MaSP = x.MaSP, TenSP = x.TenSP, IsInKho = x.IsInKho, ID = x.ID })
                }, JsonRequestBehavior.AllowGet);
            }

            var lstP = db.SanPhams.Where(p => p.MaSP != null && p.Disable == null).ToList();
            foreach (var sanpham in lstP)
            {
                var temp = new SanPham();
                temp.IsInKho = sanpham.CheckSanPhamInKho(id);
                temp.ID = sanpham.ID;
                temp.MaSP = sanpham.MaSP;
                temp.TenSP = sanpham.TenSP;
                SanPhams.Add(temp);
            }
            return Json(new
            {
                data = SanPhams.Select(x => new { MaSP = x.MaSP, TenSP = x.TenSP, IsInKho = x.IsInKho, ID = x.ID })
            }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        [Authorize(Roles = "Administrator")]
        public JsonResult Index(string chk, int khoid)
        {
            Dictionary<int, int> listSanPham = new Dictionary<int, int>();
            string[] chks = chk.Split(new string[] { "#" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string key in chks)
            {
                if (!listSanPham.ContainsKey(Convert.ToInt32(key)))
                    listSanPham.Add(Convert.ToInt32(key), Convert.ToInt32(key));
            }
            string result = string.Empty;
            var SanPhams = db.SanPhams.ToList();
            foreach (var sanpham in SanPhams)
            {
                if (listSanPham.ContainsKey(sanpham.ID))
                {
                    if (sanpham.CheckSanPhamInKho(khoid))
                    {
                        ////San pham co' san trong kho, do nothing
                    }
                    else
                    {
                        ////Them san pham moi vao kho
                        SanPhamInKho sanPhamInKho = new SanPhamInKho();
                        sanPhamInKho.KhoID = khoid;
                        sanPhamInKho.SanPhamID = sanpham.ID;
                        sanPhamInKho.SoLuong = 0;
                        db.SanPhamInKhoes.Add(sanPhamInKho);
                        db.SaveChanges();
                    }
                }
                else
                {
                    if (sanpham.CheckSanPhamInKho(khoid))
                    {
                        ////Xoa' san pham cu khoi kho
                        var sanphaminkho = db.SanPhamInKhoes.Where(s => s.KhoID == khoid && s.SanPhamID == sanpham.ID).FirstOrDefault();
                        if (sanphaminkho.SoLuong > 0)
                        {
                            result += string.Format("Không thể bỏ sản phẩm \"{0}\" khỏi kho vì còn {1} trong kho.", sanpham.MaSP, sanphaminkho.SoLuong);
                        }
                        else
                        {
                            db.SanPhamInKhoes.Remove(sanphaminkho);
                            db.SaveChanges();
                        }
                    }
                    else
                    {
                        ////San pham ko co' trong kho, do nothing
                    }
                }
            }

            return Json(new { msg = "success" + result }, JsonRequestBehavior.AllowGet);
        }

        //Popup nhap kho
        [Authorize(Roles = "Administrator,Staff")]
        public ActionResult SanPhamConTrongCuaHang()
        {
            return View();
        }

        [Authorize(Roles = "Administrator,Staff")]
        public JsonResult SanPhamConTrongCuaHangGet()
        {
            var khoes = GetCurrentCuaHang().Khoes;
            var khoIDs = new List<int>();
            foreach (Kho kho in khoes)
            {
                khoIDs.Add(kho.Id);
            }

            var spiks = db.SanPhamInKhoes.Where(p => p.SoLuong > 0 && p.SanPham.MaSP != null && p.SanPham.Disable == null && khoIDs.Contains(p.KhoID)).ToList();
            
            return Json(new
            {
                data = spiks.Select(x => new { MaSP = x.SanPham.MaSP, SoLuong = x.SoLuong, DonVi = x.SanPham.DonVi, ID = x.ID })
            }, JsonRequestBehavior.AllowGet);
        }

        //Popup xuat kho
        [Authorize(Roles = "Administrator,StaffXuatKho")]
        public ActionResult SanPhamTheoKho()
        {
            return View();
        }

        [Authorize(Roles = "Administrator,StaffXuatKho")]
        [HttpPost]
        public JsonResult SanPhamTheoKho(int page, int rows, string sidx, string sord, bool _search, string filters)
        {
            CuaHang curCuaHang = GetCurrentCuaHang();
            var khoes = curCuaHang.Khoes.OrderBy(p => p.TenKho);
            var khoIDs = new List<int>();
            foreach (var kho in khoes)
            {
                khoIDs.Add(kho.Id);
            }

            var SanPham = db.SanPhamInKhoes.OrderBy(p => p.SanPham.MaSP).Where(p => p.SanPham.MaSP != null && p.SanPham.Disable == null && khoIDs.Contains(p.KhoID)).ToList() as IEnumerable<SanPhamInKho>;

            if (_search)
            {
                FiltersJq f = (!_search || string.IsNullOrEmpty(filters)) ? null : JsonConvert.DeserializeObject<FiltersJq>(filters);
                for (int i = 0; i < f.rules.Count; i++)
                {
                    string field = f.rules[i].field;
                    string data = f.rules[i].data;
                    switch (field)
                    {
                        case "MaSP": SanPham = SanPham.Where(p => p.SanPham.MaSP.ToLower().Contains(data.ToLower())); break;
                        case "TenSP": SanPham = SanPham.Where(p => p.SanPham.TenSP.ToLower().Contains(data.ToLower())); break;
                        default: SanPham.Where(p => p.SanPham.MaSP.ToLower().Contains(data.ToLower())); break;
                    }
                }

            }

            var count = SanPham.Count<SanPhamInKho>();
            int total;
            if (count == 0)
                total = 0;
            else
                total = (int)Math.Ceiling((decimal)count / rows);

            var pagedResult = SanPham.Skip(rows * (page - 1)).Take(rows).ToList();

            var result = new
            {
                total = total,
                page = page,
                records = count,
                rows = pagedResult.Select(x => new { x.ID, x.SanPham.MaSP, x.SoLuong, x.SanPham.DonVi, x.SanPham.GiaNhap })

            };
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        [Authorize(Roles = "Administrator,Staff,StaffXuatKho")]
        public ExcelResult Export(string sidx, string sord)
        {
            try
            {
                var listSanPhams = db.SanPhams.OrderBy(p => p.MaSP).Where(p => p.MaSP != null && p.Disable == null).ToList() as IEnumerable<SanPham>;

                DataTable tablenew = new DataTable("SanPham");
                tablenew.Columns.Add("Sản phẩm");
                tablenew.Columns.Add("Giá", typeof(decimal));
                tablenew.Columns.Add("Số lượng", typeof(string));
                tablenew.Columns.Add("Thành tiền", typeof(decimal));
                tablenew.Columns.Add("Đơn vị");

                int currentCuaHangID = Convert.ToInt32(Session["CuaHangID"]);
                CuaHang cuaHang = db.CuaHangs.Find(currentCuaHangID);
                List<int> khoIDs = new List<int>();
                foreach (Kho kho in cuaHang.Khoes)
                {
                    khoIDs.Add(kho.Id);
                }

                foreach (SanPham sanpham in listSanPhams)
                {
                    decimal gianhap = Util.ConvertCurrencyToMoney(sanpham.GiaNhap);
                    int soluong = 0;
                    string soluonginkho = string.Empty;
                    var spik = sanpham.SanPhamInKhoes.Where(s => khoIDs.Contains(s.KhoID));
                    foreach (var sanPhamInKho in spik)
                    {
                        soluong += sanPhamInKho.SoLuong;
                        soluonginkho += sanPhamInKho.Kho.TenKho + " : " + sanPhamInKho.SoLuong + Environment.NewLine;
                    }

                    if (!string.IsNullOrEmpty(soluonginkho))
                    {
                        DataRow newrow = tablenew.NewRow();
                        newrow["Sản phẩm"] = Convert.ToString(sanpham.TenSP);
                        newrow["Giá"] = gianhap;
                        newrow["Đơn vị"] = Convert.ToString(sanpham.DonVi);
                        newrow["Số lượng"] = soluonginkho;
                        newrow["Thành tiền"] = gianhap * soluong;
                        tablenew.Rows.Add(newrow);
                    }
                }

                string excelFilename = "Tồn kho " + DateTime.Now.ToString("dd/MM/yyyy") + ".xlsx";

                var stream = CreateExcelFile.CreateExcelDocument(tablenew, excelFilename);

                return new ExcelResult()
                {
                    FileName = excelFilename,
                    Stream = stream
                };
            }
            catch (Exception ex)
            {
                ex.ToString();
                return null;
            }
        }

    }
}
